/**
 * fulihui.com Inc.
 * Copyright (c) 2015-2016 All Rights Reserved.
 */
package com.fulihui.integral.core.service;

import com.fulihui.integral.core.api.ISBaseQueryService;
import com.fulihui.integral.core.biz.conv.ISAccountDetailConvert;
import com.fulihui.integral.core.biz.model.StatQueryModel;
import com.fulihui.integral.core.biz.utils.StatQueryDateUtil;
import com.fulihui.integral.core.dal.dataobj.ISAccountDetail;
import com.fulihui.integral.core.dal.dataobj.ISAccountDetailExample;
import com.fulihui.integral.core.dal.mapper.ISAccountDetailMapper;
import com.fulihui.integral.core.dal.mapper.ext.ISAccountDetailExtMapper;
import com.fulihui.integral.core.dal.repository.ISBaseQueryRepository;
import com.fulihui.integral.core.dto.ISAccountInfoDTO;
import com.fulihui.integral.core.enums.ISAccountQueryType;
import com.fulihui.integral.core.request.*;
import com.fulihui.integral.core.result.ISAccountDetailPageResult;
import com.fulihui.integral.core.result.ISAccountInfoResult;
import com.fulihui.integral.core.result.ISAccountStatResult;
import org.near.servicesupport.result.BaseResult;
import org.near.servicesupport.result.ResultBuilder;
import org.near.servicesupport.util.ConditionValidator;
import org.near.toolkit.common.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 积分系统基础查询
 *
 * @author yunfeng.li
 * @version $Id: v 0.1 2017年04月14日 15:35 yunfeng.li Exp $
 */
@Service("iSBaseQueryService")
public class ISBaseQueryServiceImpl implements ISBaseQueryService {

    private Logger logger = LoggerFactory.getLogger(ISBaseQueryServiceImpl.class);

    @Resource
    private ISBaseQueryRepository iSBaseQueryRepository;
    @Resource
    private ISAccountDetailMapper iSAccountDetailMapper;
    @Resource
    private ISAccountDetailExtMapper iSAccountDetailExtMapper;

    /**
     * 查询个人积分余额
     *
     * @param req
     * @return
     */
    @Override
    public ISAccountInfoResult queryISAccountInfo(ISAccountInfoQueryReq req) {
        ConditionValidator.validate(req);
        ISAccountInfoDTO isAccountInfoDTO = iSBaseQueryRepository.queryISAccountInfo(req);
        ISAccountInfoResult result = new ISAccountInfoResult();
        result.setValue(isAccountInfoDTO);
        result.setErrcode(BaseResult.SUCCESS);
        return result;
    }

    /**
     * 查询个人积分当日收支数详情
     *
     * @param req
     * @return
     */
    @Override
    public ISAccountStatResult queryISAccountStat(ISAccountDetailQueryReq req) {
        ConditionValidator.validate(req);
        StatQueryModel model = timeHorizon(req);
        ISAccountStatResult result = ResultBuilder.succ(ISAccountStatResult.class);
        List<Map<String, Object>> mapList = iSAccountDetailExtMapper.statByUserId(req.getUserId(), req.getChannel(),
                model.getStartDate(), model.getEndDate());
        if (!CollectionUtils.isEmpty(mapList)) {
            mapList.forEach(item -> {
                if (item.size() > 0) {
                    String amount = item.get("amount").toString();
                    String op_type = item.get("op_type").toString();
                    if (StringUtil.equals("SUB", op_type)) {
                        result.setSubAmount(Long.valueOf(amount));
                    } else if (StringUtil.equals("ADD", op_type)) {
                        result.setAddAmount(Long.valueOf(amount));
                    }
                }
            });
        }
        return result;
    }

    /**
     * 查询个人积分交易明细
     *
     * @param req
     * @return
     */
    @Override
    public ISAccountDetailPageResult queryISAccountDetail(ISAccountDetailPageReq req) {
        ConditionValidator.validate(req);
        ISAccountDetailExample example = new ISAccountDetailExample();
        ISAccountDetailExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(req.getUserId());
        Date date = StatQueryDateUtil.getNowDate();
        criteria.andGmtCreateGreaterThanOrEqualTo(date);

        if (StringUtil.isNotBlank(req.getIsAccountType())) {
            criteria.andIsAccountTypeEqualTo(req.getIsAccountType());
        }

        long countByExample = iSAccountDetailMapper.countByExample(example);

        example.setOffset(req.start4Mysql());
        example.setLimit(req.getRows());
        example.setOrderByClause("gmt_create desc");
        List<ISAccountDetail> wxSendTemplateLogs = iSAccountDetailMapper
                .selectByExample(example);

        ISAccountDetailPageResult result = ResultBuilder.succPageResult(ISAccountDetailPageResult.class,
                req.getPage(), req.getRows(), Integer.parseInt(countByExample + ""));
        result.setDetails(ISAccountDetailConvert.convert2List(wxSendTemplateLogs));
        return result;
    }

    /**
     * 根据渠道查询用户时间范围类的积分
     *
     * @param request
     * @return
     */
    @Override
    public ISAccountStatResult queryISByChannel(ISAccountQueryReq request) {
        ConditionValidator.validate(request);
        ISAccountStatResult result = ResultBuilder.succ(ISAccountStatResult.class);
        Long amount = iSAccountDetailExtMapper.statByChannel(request.getUserId(), request.getChannel(),
                request.getStartTime(), request.getEndTime());
        result.setAddAmount(amount == null ? 0L : amount);
        return result;
    }

    @Override public ISAccountDetailPageResult queryDetail(ISAccountDetailReq request) {
        ConditionValidator.validate(request);
        ISAccountDetailExample example = new ISAccountDetailExample();
        ISAccountDetailExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(request.getUserId());
        if(request.getStartTime() != null){
            criteria.andGmtCreateGreaterThanOrEqualTo(request.getStartTime());
        }
        if(request.getEndTime() != null){
            criteria.andGmtCreateLessThanOrEqualTo(request.getEndTime());
        }
        if (StringUtil.isNotBlank(request.getIsAccountType())) {
            criteria.andIsAccountTypeEqualTo(request.getIsAccountType());
        }

        long countByExample = iSAccountDetailMapper.countByExample(example);

        example.setOffset(request.start4Mysql());
        example.setLimit(request.getRows());
        example.setOrderByClause("gmt_create desc");

        List<ISAccountDetail> wxSendTemplateLogs = iSAccountDetailMapper
                .selectByExample(example);
        ISAccountDetailPageResult result = ResultBuilder.succPageResult(ISAccountDetailPageResult.class,
                request.getPage(), request.getRows(), Integer.parseInt(countByExample + ""));
        result.setDetails(ISAccountDetailConvert.convert2List(wxSendTemplateLogs));
        return result;
    }

    /**
     * 分发条件
     *
     * @param req
     * @return
     */
    private StatQueryModel timeHorizon(ISAccountDetailQueryReq req) {
        ISAccountQueryType type = ISAccountQueryType.getEnumByCode(req.getQueryType());
        switch (type) {
            case MONTH:
                String queryMonth = req.getQueryMonth();
                try {
                    StatQueryModel statQueryModel = StatQueryDateUtil.getMonthFirstAndLastDay(queryMonth);
                    return statQueryModel;
                } catch (ParseException e) {
                    logger.error("parse date is error!");
                }
            case TODAY:
                StatQueryModel statQueryModel = StatQueryDateUtil.getNowDay();
                return statQueryModel;
            case CUSTOM:
                StatQueryModel model = new StatQueryModel();
                model.setStartDate(req.getStartTime());
                model.setEndDate(req.getEndTime());
                return model;
            default:
                logger.error("Unsupported Query Type:{}", req.getQueryType());
                throw new UnsupportedOperationException(
                        "Unsupported Query Type:" + req.getQueryType());
        }
    }
}
